import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
})

// 请求拦截器
service.interceptors.request.use((config) => {
  // do something before request is sent
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, (error) => {
  // do something with request error
  return Promise.reject(error)
}
)

// 响应拦截器
service.interceptors.response.use((response) => {
  // do something with response data
  // 如果是文件流，则直接将Blob 对象返回
  if (response.data instanceof Blob) {
    return response.data
  }
  const { data, success, message } = response.data // 这里默认相应数据是json格式的了
  if (success) {
    /* Message({
      message,
      type: 'success',
      duration: 5 * 1000
    }) */
    return data
  } else {
    Message({
      message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(new Error(message))
  }
}, async(error) => {
  if (error.response.status === 401) {
    await store.dispatch('user/logout') // 退出登录
    Message({
      message: '登录状态已过期，请重新登录',
      type: 'error',
      duration: 5 * 1000
    })
    router.push('/login')
    return Promise.reject(error)
  }
  // do something with response error
  return Promise.reject(error)
}
)

export default service
